package com.glinsoft.ticktak.util;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.UUID;



public class Unique {

    private static final long ONE_STEP = 10;
    private static final Lock LOCK = new ReentrantLock();
    private static long lastTime = System.currentTimeMillis();
    private static short lastCount = 0;
    private static int count = 0;

    /**
     * 唯一ID
     *
     * @return
     */
    public static String nextId() {
        LOCK.lock();
        try {
            if (lastCount == ONE_STEP) {
                boolean done = false;
                while (!done) {
                    long now = System.currentTimeMillis();
                    if (now == lastTime) {
                        try {
                            Thread.currentThread();
                            Thread.sleep(1);
                        } catch (java.lang.InterruptedException e) {}
                        continue;
                    } else {
                        lastTime = now;
                        lastCount = 0;
                        done = true;
                    }
                }
            }
            count = lastCount++;
        }finally {
            LOCK.unlock();
            return lastTime+""+String.format("%03d",count);
        }
    }


    /**
     * 表名后缀
     *
     * @param id
     * @return
     */
    private final static int scale = 10; // 当前分表规模:10,20,30

    public static String tableSuffix(String id){
        if(id==null || id.trim().equals("")){
            return null;
        }
        return "_" + String.valueOf(Integer.valueOf(id.substring(id.length()-1))+scale-10);
    }



    /**
     * 获取唯一ID
     *
     * @return
     */
    public static String UUID(){
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-","");
    }


}
